package com.mew.common.config;

import com.mew.common.exception.MewException;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

public class NicknameUtil {
    private final static  ConcurrentHashMap<Integer, String> nameMap = new ConcurrentHashMap<>();
    private  static int randomNum = Math.abs(new Random().nextInt(380));
    private NicknameUtil(){}

    public static String getName(){
        if (null == nameMap || nameMap.isEmpty()){
            initializeName();
        }
        //当前名字数量
        int length = nameMap.size();
        randomNum ++;
        if (randomNum > length -1){
            randomNum = 0;
        }
        return nameMap.get(randomNum);
    }

    public static void initializeName()throws MewException {
        synchronized (NicknameUtil.class){
            try {
                String path = System.getProperty("user.dir") +  "/external/name.txt";
                FileInputStream fileInputStream  = new FileInputStream(new File(path));
                InputStreamReader  in = new InputStreamReader(fileInputStream, "UTF-8");
                BufferedReader br = new BufferedReader(in);
                String s;
                int i = 0;
                while ((s = br.readLine())!=null){
                    if (StringUtils.isNotEmpty(s)){
                        nameMap.put(i, s);
                        i++;
                    }
                }
            } catch (FileNotFoundException e) {
                throw new MewException(e.getMessage());
            } catch (UnsupportedEncodingException e) {
                throw new MewException(e.getMessage());
            } catch (IOException e) {
                throw new MewException(e.getMessage());
            }
        }

    }
}
